package servlets;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA.
 * User: Joshua
 * Date: 7/20/12
 * Time: 6:06 PM
 * A servlet that queries the database to gather all campaigns belonging to this
 * user and selected ruleset.
 */
public class FetchCampaigns extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(); //to store session variables

        //get param information
        String userid = request.getParameter("userid");
        String ruleset = request.getParameter("ruleset");
        try {
            Connection conn = getConnection();

            //get a map of all the campaigns and characters belonging to this ruleset
            //and user
            TreeMap<String, ArrayList<String>> characters = getCharacters(conn, userid,
                    ruleset);

            //persist this userid and ruleset
            session.setAttribute("userid", userid);
            session.setAttribute("ruleset", ruleset);

            //send along the map of campaigns and characters
            session.setAttribute("characters", characters);
            session.setAttribute("campaigns", characters.keySet());

            response.sendRedirect(response.encodeRedirectURL("/charSelect.jsp"));
        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


    }

    ///////////////////////////////////////////////////////////////////////////
    //getConnection
    //params: none
    //returns: a database connection
    private Connection getConnection() throws SQLException {

        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", "steward");
        connectionProps.put("password", "readOnly");


        conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/squire",
                connectionProps);

        System.out.println("Connected to database");
        return conn;
    }

    ////////////////////////////////////////////////////////////////////////////
    //getCampaigns
    //parameters: the Database connection, userid, and ruleset
    //returns: a map of strings to sets of strings
    //description: Queries the database to find all campaign instances that
    //belong to this ruleset that the user is participating in and returns those
    // instances mapped to the characters belonging to that instance and those
    // players.
    private TreeMap<String, ArrayList<String>> getCharacters(Connection conn, String userid, String ruleset){
        TreeMap<String, ArrayList<String>> characters = new TreeMap<String, ArrayList<String>>();
        PreparedStatement getChars;
        String campaign;
        String query =
                "select campaign, name " +
                "from characters " +
                "where ruleset = ? and owner = ?";

        try{
            getChars = conn.prepareStatement(query);
            getChars.setString(1, ruleset);
            getChars.setString(2, userid);

            ResultSet results = getChars.executeQuery();

            //gather up campaigns and characters
            while(results.next()){
                campaign = results.getString("campaign");

                //check if this already exists in the Map
                if(characters.containsKey(campaign))
                    characters.get(campaign).add(results.getString("name"));
                else{
                    ArrayList<String> charsPerSet = new ArrayList<String>();
                    charsPerSet.add(results.getString("name"));
                    characters.put(campaign, charsPerSet);
                }
            }
        }catch(SQLException sql){
            ArrayList<String> errorMessage = new ArrayList<String>();
            errorMessage.add("Query threw an sql exception: "+sql.getMessage());

            characters.put("error", errorMessage);
        }

        return characters;
    }//end getCharacters

    ///////////////////////////////////////////////////////////////////////
    //constructTable
    //parameters: a map of campaigns and characters
    //returns: a string of html
    //description: constructs the table that will form the body of the
    //character selection page, with each cell containing a subtable of
    //the characters belonging to that campaign and user.
    private String constructTable(TreeMap<String, ArrayList<String>> characters){
        //the basis of the body will be a table
        StringBuilder buffer =  new StringBuilder(
                "<table class=\"body\">" +
                        "<tr>" +
                        "<th>Campaigns</th>" +
                        "</tr>");

        if(characters.isEmpty()){

        }else{
            //add in each campaign with a character subtable
            Set<String> keyset = characters.keySet();
            for(String key : keyset){
                ArrayList<String> names = characters.get(key);
                buffer.append("<tr>");
                buffer.append("<td class=\"charName\" onclick=\"\">");
                buffer.append(key);
                buffer.append("</td>");
                buffer.append("</tr>");
                buffer.append("<tr class=\"subtable\">");
                buffer.append("<td>");
                //subtable
                buffer.append("<table class=\"subtable\">");
                for(String name : names){
                    buffer.append("<tr>");
                    buffer.append("<td>");
                    buffer.append(name);
                    buffer.append("</td>");
                }
                buffer.append("</td>");
                buffer.append("</tr>");
            }
            buffer.append("</table>");
        }

        return buffer.toString();
    }
}
